#include <QMessageBox>
#include <QSqlError>

#include "dbadmin.h"

DbAdmin::DbAdmin()
{
	db = QSqlDatabase::addDatabase("QSQLITE");
}

DbAdmin::~DbAdmin()
{
	db.close();
}

bool DbAdmin::createConnection(QString file ,bool createDbTables )
{
    closeConnection();
    	
    db.setDatabaseName(file);
    if( !db.open() ) {
        QMessageBox::critical( 0, QObject::tr( "Error" ), 
        QObject::tr( "Could not open database; driver said: %1, database said: %2" )
        .arg( db.lastError().driverText() ).arg( db.lastError().databaseText() ) );
        return 0;
    }
    if (createDbTables) createTables();
    	return 1;
}

void DbAdmin::closeConnection()
{
	if ( db.isOpen() ) db.close();
}

void DbAdmin::createTables()
{
	QSqlQuery query;
    query.exec("create table saturday( id int,subject int,fromTime int,"
     			"toTime int,place int, teacher int)");
    query.exec("create table sunday( id int,subject int,fromTime int,"
     			"toTime int,place int, teacher int)");
    query.exec("create table monday( id int,subject int,fromTime int,"
     			"toTime int,place int, teacher int)");
    query.exec("create table tuesday( id int,subject int,fromTime int,"
     			"toTime int,place int, teacher int)");
    query.exec("create table wednesday( id int,subject int,fromTime int,"
     			"toTime int,place int, teacher int)");
    query.exec("create table thursday( id int,subject int,fromTime int,"
     			"toTime int,place int, teacher int)");
     			     			     			
    query.exec("create table subjects ( id int,name varchar(50))");
    query.exec("create table places ( id int,name varchar(50))");
    query.exec("create table teachers ( id int,name varchar(50))");
    query.exec("create table times ( id int,name varchar(10) )");
}
